<template>
  <div class="calculator">
    <h1>计算器</h1>
    <div class="input-group">
      <label>数字1：</label>
      <input type="number" v-model.number="num1" @input="handleNum1Change" />
    </div>
    <div class="input-group">
      <label>数字2：</label>
      <input type="number" v-model.number="num2" @input="handleNum2Change" />
    </div>
    <div class="input-group">
      <label>运算符：</label>
      <select v-model="operator" @change="handleOperatorChange">
        <option value="+">+</option>
        <option value="-">-</option>
        <option value="*">*</option>
        <option value="/">/</option>
      </select>
    </div>
    <button @click="handleCalculate">确定</button>
    <div class="result">结果：{{ result }}</div>
  </div>
</template>

<script setup lang="ts">
import { useCalculatorStore } from './stores/calculatorStore'
// 1. 导入 storeToRefs
import { storeToRefs } from 'pinia'

const store = useCalculatorStore()

// 2. 使用 storeToRefs 解构，保持响应式
const { num1, num2, operator, result } = storeToRefs(store)

// 处理数字 1 变化
const handleNum1Change = (e: Event) => {
  store.setNum1((e.target as HTMLInputElement).valueAsNumber)
}

// 处理数字 2 变化
const handleNum2Change = (e: Event) => {
  store.setNum2((e.target as HTMLInputElement).valueAsNumber)
}

// 处理运算符变化
const handleOperatorChange = (e: Event) => {
  store.setOperator((e.target as HTMLSelectElement).value as '+' | '-' | '*' | '/')
}

// 处理计算逻辑（点击按钮时执行）
const handleCalculate = () => {
  store.calculate() // 调用仓库的计算方法，更新 result
}
</script>

<style scoped>
.calculator {
  max-width: 300px;
  margin: 50px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 8px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
.input-group {
  margin-bottom: 15px;
}
label {
  display: block;
  margin-bottom: 5px;
}
input, select {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}
button {
  width: 100%;
  padding: 10px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
.result {
  margin-top: 15px;
  padding: 10px;
  background: #f0f8ff;
  border-radius: 4px;
  text-align: center;
}
</style>